﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineEducation.Data;
using OnlineEducation.Models.JQueryTable;
using OnlineEducation.Helpers.JQueryTable;
using AutoMapper;
using OnlineEducation.Controllers;

namespace OnlineEducation.Areas.Controllers
{
    [Area("Code")]
    [Route("[controller]/[action]")]
    [Authorize]
    public class CodeManagerController : BaseController
    {
        
        private readonly ApplicationDbContext _context;
        private readonly ILogger _logger;
        private readonly IMapper _mapper;
        public CodeManagerController(ApplicationDbContext context, ILogger<CodeManagerController> logger, IMapper mapper)
        {
            _context = context;
            _logger = logger;
            _mapper = mapper;
        }


        public IActionResult Index()
        {

            return View( );
        }

        [HttpPost]
        public IActionResult GetAll(DTParameters param)
        {
            var query = _context.Codes.Where(n => n.Category != Constants.Code.Subject);

            var newQuery = new SortHelper<OnlineEducation.Data.Entities.Code>().Apply(query, param);

            var items = newQuery.Skip(param.Start).Take(param.Length).ToArray();

            var count = newQuery.Count();

            return Json(new DTResult<OnlineEducation.Data.Entities.Code>
            {
                draw = param.Draw,
                data = items,
                recordsFiltered = count,
                recordsTotal = count
            });
        }
        [HttpGet("{id?}")]
        public async Task<IActionResult> AddEdit(int? id)
        {
            if (id.HasValue)
            {
                return View(await _context.Codes.FindAsync(id));
            }
            else
            {
                var template = new OnlineEducation.Data.Entities.Code();

                return View(template);

            }
        }
        [HttpPost]
        public async Task<IActionResult> Save([FromBody]OnlineEducation.Data.Entities.Code data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (data.ID == 0)
            {
                try
                {
                    _context.Add(data);

                    await _context.SaveChangesAsync();

                    return Json(new { success = true, message = "新增数据成功." });

                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message });
                }

            }
            else
            {
                try
                {
                    var code = _context.Codes.Find(data.ID);

                    _mapper.Map(data, code);

                    _context.Update(code);

                    await _context.SaveChangesAsync();

                    return Json(new { success = true, message = "更新数据成功." });
                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message });
                }

            }
        }

        [HttpPost("{id}")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var code = await _context.Codes.SingleOrDefaultAsync(m => m.ID == id);
                if (code == null)
                {
                    return NotFound();
                }

                _context.Codes.Remove(code);
                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "删除数据成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }

        [HttpPost("{id}")]
        public async Task<IActionResult> ChangeStatus(int? id)
        {
            if (!id.HasValue)
            {
                return BadRequest("id为空");
            }

            try
            {
                var code = await _context.Codes.FindAsync(id.Value);

                if (code == null)
                {
                    return NotFound("未找到参数");
                }
                if (code.Status == 1)
                {
                    code.Status = 0;
                }
                else
                {
                    code.Status = 1;
                }

                _context.Update(code);

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "状态变更成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }
    }
}